package utils

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"math"
	"net/url"
	"strconv"
)

func UniqueIds(ids []uint64) []uint64 {
	var (
		arr  = make([]uint64, 0, len(ids))
		temp = make(map[uint64]bool)
	)
	for _, v := range ids {
		if ok := temp[v]; ok {
			continue
		}
		temp[v] = true
		arr = append(arr, v)
	}
	return arr
}

func StrToInt(str string) int {
	num, err := strconv.Atoi(str)
	if err != nil {
		return 0
	}
	return num
}

// DifferenceSlice 比较两个切片，返回他们的差集
func DifferenceSlice[T comparable](s1, s2 []T) []T {
	m := make(map[T]bool)
	for _, item := range s1 {
		m[item] = true
	}
	var diff []T
	for _, item := range s2 {
		if _, ok := m[item]; !ok {
			diff = append(diff, item)
		}
	}
	return diff
}

// InSlice 元素是否存在于切片中
func InSlice[K comparable](slice []K, key K) bool {
	for _, v := range slice {
		if v == key {
			return true
		}
	}
	return false
}

// IsURL 是否是url地址
func IsURL(u string) bool {
	if _, err := url.ParseRequestURI(u); err != nil {
		return false
	}
	l, err := url.Parse(u)
	if err != nil || l.Scheme == "" || l.Host == "" {
		return false
	}
	return true
}

// GetAddr 获取请求中的请求地址，协议+域名/IP:端口
func GetAddr(ctx context.Context) string {
	r := g.RequestFromCtx(ctx)
	host := r.Header.Get("X-Forwarded-Host")
	if host == "" {
		host = r.Header.Get("X-Host")
	}
	if host == "" {
		host = r.Host
	}
	return "//" + host
}

// PrecisionRound 精确四舍五入
func PrecisionRound(num float64, precision int) float64 {
	shift := math.Pow(10, float64(precision))
	// 处理符号确保正确四舍五入
	rounded := math.Copysign(math.Trunc(math.Abs(num)*shift+0.5), num)
	return rounded / shift
}

// GetClientIp 获取客户端IP
func GetClientIp(ctx context.Context) string {
	return g.RequestFromCtx(ctx).GetClientIp()
}
